package com.github.common.extend.demo.config.filetask;

import java.io.*;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

/**
 * 文件构造器
 * @author wangjj7
 * @date 2023/8/25
 * @description
 */
public class FileSourceBuilder implements DataSourceBuilder<FileInputStream> {

    //是否已经构建
    private boolean init;

    //文件写入地址
    private final File tmpWriteFile;

    //文件写入函数
    private final BiConsumer<FileOutputStream ,Consumer<Double>> fileWriter;

    public FileSourceBuilder(File tmpWriteFile , BiConsumer<FileOutputStream ,Consumer<Double>> fileWriter) {
        Objects.requireNonNull(tmpWriteFile);
        Objects.requireNonNull(fileWriter);

        this.tmpWriteFile = tmpWriteFile;
        this.fileWriter = fileWriter;
    }

    @Override
    public void buildSource(Consumer<Double> rateRefresh) {
        if (init){
            return;
        }
        synchronized (this){
            if (init){
                return;
            }
            File tmpWriteExcelDir = tmpWriteFile.getParentFile();
            if (!tmpWriteExcelDir.exists()){
                tmpWriteExcelDir.mkdirs();
            }
            try (FileOutputStream fileOutputStream = new FileOutputStream(tmpWriteFile)){
                fileWriter.accept(fileOutputStream ,rateRefresh);
            } catch (IOException e) {
                throw new IllegalStateException("任务生成失败" ,e);
            }
            init = true;
        }
    }

    @Override
    public FileInputStream inputStream() {
        try {
            return new FileInputStream(tmpWriteFile);
        } catch (FileNotFoundException e) {
            throw new IllegalStateException(e);
        }
    }

    //文件清理
    public void clear(){
        if (tmpWriteFile.exists() && tmpWriteFile.isFile()){
            tmpWriteFile.delete();
        }
    }

}
